package com.itheima.controller;

import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

// 被扫描
// 返回的数据结果= json
// 切面
@RestControllerAdvice
public class ExceptionAdviceHandler {

    //dao 异常捕获异常捕获  DataIntegrityViolationException
    @ExceptionHandler(DataIntegrityViolationException.class)
    public Result dive(DataIntegrityViolationException e){

        System.out.println(e.getMessage());
        String msg = "反正是你的问题";
        if(e.getMessage().contains("Data too long")){
            msg = "你输入的字段太长了";
        }

        return new Result(Code.DAO_ERR,null,msg);
    }


    // 业务异常
    @ExceptionHandler(BusinessException.class)
    public Result business(BusinessException e){

        System.out.println("BusinessException = "+e.getMessage());
        e.printStackTrace();
        return new Result(e.getCode(),null,e.getMessage());
    }


    // 系统异常
    @ExceptionHandler(SystemException.class)
    public Result system(SystemException e){
        // 1. 安抚
        // 2. 发邮件 开发、运维、测试、前端
        // 3. 记录日志
        System.out.println("SystemException = "+e.getMessage());
        e.printStackTrace();
        return new Result(e.getCode(),null,e.getMessage());
    }

    //其他异常
    //（拦截的异常）
    @ExceptionHandler(Exception.class)
    public Result exception(Exception e){
        System.out.println(e.getMessage());
        e.printStackTrace();
        return new Result(Code.ERR_ERR,null,"网络出现了问题，请重试~");
    }
}
